package com.hc.sss.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hc.sss.common.ResultMap;
import com.hc.sss.mapper.RedEnvelopeMapper;
import com.hc.sss.mapper.RedEnvelopeUserMapper;
import com.hc.sss.pojo.RedEnvelope;
import com.hc.sss.pojo.RedEnvelopeUser;
import com.hc.sss.service.RedEnvelopeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class RedEnvelopeServiceImpl implements RedEnvelopeService {

    @Autowired
    RedEnvelopeMapper redEnvelopeMapper;//红包mapper

    @Autowired
    RedEnvelopeUserMapper redEnvelopeUserMapper;//红包发放mapper

    //添加红包
    public int insertRedEnvelope(RedEnvelope redEnvelope) {
        return redEnvelopeMapper.insertRedEnvelope(redEnvelope);
    }

    /*查询所有红包+分页*/
    public ResultMap<RedEnvelope> findRedEnvelopeList(Map<String, Object> paramMap) {
        ResultMap<RedEnvelope> resultMap = new ResultMap<RedEnvelope>();
        Integer page = 1;
        Integer limit = 5;
        if (paramMap.get("page") != null && !"".equals(paramMap.get("page"))) {
            page = Integer.valueOf(paramMap.get("page").toString());
        }
        if (paramMap.get("limit") != null && !"".equals(paramMap.get("limit"))) {
            limit = Integer.valueOf(paramMap.get("limit").toString());
        }
        PageHelper.startPage(page, limit);
        List<RedEnvelope> list = redEnvelopeMapper.findRedEnvelopeList(paramMap);
        PageInfo<RedEnvelope> info = new PageInfo<>(list);
        resultMap.setData(list);
        resultMap.setCount((int)info.getTotal());
        return resultMap;
    }

    /*修改红包*/
    public int updateRedEnvelope(RedEnvelope redEnvelope) {
        return redEnvelopeMapper.updateRedEnvelope(redEnvelope);
    }


    /*发放红包*/
    public int redEnvelopeSend(Integer reId, List<Integer> userId) {
        RedEnvelopeUser redEnvelopeUser = new RedEnvelopeUser();
        redEnvelopeUser.setReuReId(reId);
        for(Integer i:userId){
            redEnvelopeUser.setReuUserId(i);
           int j = redEnvelopeUserMapper.insertRedEnvelopeUser(redEnvelopeUser);
            if(j<0){
                return -1;
            }
        }
        return 1;
    }

    /*删除红包*/
    public int deleteRedEnvelope(RedEnvelope redEnvelope) {
        int result = redEnvelopeMapper.updateRedEnvelope(redEnvelope);
        if(result > 0){
            redEnvelopeUserMapper.deleteRedEnvelopeUser(redEnvelope.getReId());
        }
        return result;
    }


}
